<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="showSearch">
        <el-card shadow="hover">
          <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
            <!-- 循环遍历对象 -->
            <template v-for="(itemField, indexField) in onlineField" >
              <el-form-item  v-if="itemField && itemField.query"
              :label="itemField.columnComment"  :prop="itemField.columnName" >
                <template v-if="itemField.htmlType == 'input'">
                  <el-input v-model="queryParams.params[itemField.columnName]" :placeholder="itemField.columnComment" clearable style="width: 200px" @keyup.enter="handleQuery" />
                </template>
                <template v-if="itemField.commonDictCode != null && itemField.htmlType == 'select'">
                  <el-select v-model="queryParams.params[itemField.columnName]" :placeholder="itemField.columnComment" clearable style="width: 200px">
                    <el-option v-for="dict in itemField.commonDictCode" :key="dict.id" :label="dict.name" :value="dict.id" />
                  </el-select>
                </template>
              </el-form-item>
            </template>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:notice:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate(row)" v-hasPermi="['system:notice:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:notice:remove']">
              删除
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="onlineList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <!-- 循环遍历对象 -->
          <template v-for="(itemField, indexField) in onlineField" >
            <el-table-column :key="indexField" v-if="itemField && itemField.list"
            :label="itemField.columnComment" align="center" :prop="itemField.columnName" >
              <template #default="scope" v-if="itemField.commonDictCode != null">
                <disp-tag :options="itemField.commonDictCode" :value="scope.row[itemField.columnName]" />
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:notice:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:notice:remove']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>

      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="880px" append-to-body>
      <el-form ref="formRef" :model="form.data"  :rules="rules" label-width="200px">
        <el-row>
          <el-col :span="24" v-for="(itemField, indexField) in onlineField" :key="indexField">
            <el-form-item :label="itemField.columnComment" v-if="itemField.insert || itemField.isEdit == '1'">
              <component :is="getComponentType(itemField.htmlType)" v-model:value="form.data[itemField.columnName]" :key="indexField" :nm="itemField" @common-component="commonComponent" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(formRef)">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OnlineTest" lang="ts">
import { nextTick } from 'vue';
import { listOnlineData, getOnlineData, delOnlineData, addOrUpdateOnlineData } from "@/api/online";
import { OnlineForm, OnlineQuery, OnlineVO } from "@/api/online/types";
//import { dispTag } from "../components/DispTag/index.vue";
import { useFlowable } from '@/views/workflow/hooks/useFlowable';
import { useOnline } from '@/views/workflow/hooks/useOnline'

const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { getFormComponent } = useFlowable();
const { getComponentType } = useOnline()
const { sys_notice_status, sys_notice_type } = toRefs<any>(proxy?.useDict("sys_notice_status", "sys_notice_type"));

const onlineList = ref<any>([]);
const onlineField = ref<any>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const formRef = ref<ElFormInstance>();


const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const queryParams = reactive<any>({
    pageNum: 1,
    pageSize: 10,
    params: {}
})

const form = reactive<any>({
  data: {}
});

const rules = reactive<any>({});

const tableName = ref('');
const tableId = ref(0);
// 在组件中新增主键字段名变量
const pkName = ref('');

/** 查询公告列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOnlineData(tableId.value, tableName.value, queryParams);
  onlineList.value = res.rows;
  onlineField.value = res.map.info.columnsVo;
  //form.data = onlineField.value;
  console.log("getList onlineField",onlineField.value)
  // 查找主键字段
  const pkField = onlineField.value.find(field => field.isPk)?.columnName;
  pkName.value = pkField || 'id'; // 默认使用'id'作为主键名
  total.value = res.total;
  loading.value = false;
}
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}
/** 表单重置 */
const reset = () => {
  formRef.value?.resetFields();
  form.data = reactive({});
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  console.log("handleQuery queryParams",queryParams)
  getList();
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}
/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map(item => item[pkName.value]); // 使用动态主键字段
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
}
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加";
}
/**修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset();
  // 获取主键字段名（假设在getList中已获取并存储在pkName.value中）
  const pkField = pkName.value;
  // 获取要修改的ID
   const onlineId = row ? row[pkField] : ids.value[0];
  const { data } = await getOnlineData(tableId.value, tableName.value, onlineId);
  console.log("handleUpdate data",data)
  Object.assign(form.data, data);
  dialog.visible = true;
  dialog.title = "修改";
}
/** 提交按钮 */
const submitForm = async () => {
  console.log("submitForm form.data", form.data);
  formRef.value?.validate(async (valid, fields) => {
    if (valid) {
      console.log("submitForm form.data", form.data);
      console.log("submitForm tableId.value", tableId.value);
      await addOrUpdateOnlineData(tableId.value, tableName.value, form.data);
      proxy?.$modal.msgSuccess("新增或修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
    // 获取主键字段名（假设在getList中已获取并存储在pkName.value中）
    const pkField = pkName.value;
    // 获取要删除的ID数组
    const deleteIds = row ? [row[pkField]] : ids.value;
    if (deleteIds.length === 0) {
      proxy?.$modal.msgWarning('请选择要删除的数据');
      return;
    }
    try {
      await proxy?.$modal.confirm('是否确认删除选中的数据？');
      // 调用删除API，传递表ID、表名和要删除的ID数组
      console.log("handleDelete deleteIds",deleteIds)
      await delOnlineData(tableId.value, tableName.value, deleteIds);
      proxy?.$modal.msgSuccess('删除成功');
      await getList(); // 刷新列表
    } catch (error) {
      // 用户取消删除或删除失败
      console.error('删除失败:', error);
    }
}

const commonComponent = (nm) => {
  console.log('commonComponent nm=', nm);
    let fieldname = nm.columnName;
    form.data[fieldname] = nm.commonDataInfo;
    console.log('form fieldname', fieldname);
    console.log('form.data[fieldname]', form.data[fieldname]);
};

onMounted(() => {
  tableId.value = route.params && route.params.tableId as string;
  tableName.value = route.params && route.params.tableName as string;
  if (tableId.value && tableName.value) {
    getList();
  }
})
</script>
